# -*- coding: utf-8 -*-
import sys
import uuid
import requests
import hashlib
import time
from rich.console import Console


YOUDAO_URL = "https://openapi.youdao.com/api"
APP_KEY = "6f00da346bd0d4b5"
APP_SECRET = "AvMmqJvfO8PCrqRWwc0qzZG60AmuPiAB"


def encrypt(signStr):
    hash_algorithm = hashlib.sha256()
    hash_algorithm.update(signStr.encode("utf-8"))
    return hash_algorithm.hexdigest()


def truncate(text):
    if not text:
        return None
    size = len(text)
    return text if size <= 20 else text[0:10] + str(size) + text[size - 10 : size]


def sed_request(data):
    headers = {"Content-Type": "application/x-www-form-urlencoded"}
    return requests.post(YOUDAO_URL, data=data, headers=headers)


def main(text):
    data = {}
    # 支持的语言 https://ai.youdao.com/DOCSIRMA/html/trans/api/wbfy/index.html
    salt = str(uuid.uuid1())
    curtime = str(int(time.time()))
    signStr = f"{APP_KEY}{truncate(text)}{salt}{curtime}{APP_SECRET}"
    sign = encrypt(signStr)
    data = {
        "from": "auto",
        "to": "auto",
        "signType": "v3",
        "curtime": curtime,
        "appKey": APP_KEY,
        "q": text,
        "salt": salt,
        "sign": sign,
        # 'vocabId' = "用户词表ID"
    }

    response = sed_request(data)

    # print(response.json())
    console = Console()
    result = response.json()["translation"]
    for i in result:
        console.print(i, style="green", new_line_start=True, end="\n\n")


if __name__ == "__main__":
    text = " ".join(sys.argv[1:])
    # print(text)
    # exit()

    main(text)
